package dk.ucn.datamatiker.jmaweather;

import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;

import android.R.integer;
import android.R.string;
import android.util.Xml;

public class LocationData
{

	private String _id;
	private String _name;
	private String _type;
	
	private LocationData(String id, String name, String type)
	{
		_id = id;
		_name = name;
		_type = type;
	}
	
	public String getId()
	{
		return _id;
	}
	
	public String getName()
	{
		return _name;
	}
	
	public String getType()
	{
		return _type;
	}
	
	public static LocationData fromCity(String cityName)
	{
		
		LocationData cityData = null;
		
		try
		{
			
			URI getCityUri = new URI("http://balder.ucn.dk/weather/Weather.asmx/SearchLocation?location=" + cityName);
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet pageGet = new HttpGet(getCityUri);
			HttpResponse response = httpClient.execute(pageGet);
			
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(response.getEntity().getContent(), null);
			
			boolean foundCity = false;
			
			// Parse xml data until we find matching city or no city at all
			while ((parser.getEventType() != XmlPullParser.END_DOCUMENT) && (!foundCity))
			{
				
				if (parser.getEventType() == XmlPullParser.START_TAG)
				{
					
					if (parser.getName().equals("Location"))
					{
					
						parser.nextTag();
						String locationId = parser.nextText();
						parser.nextTag();
						String locationDescription = parser.nextText();
						parser.nextTag();
						String locationType = parser.nextText();
						
						if (locationId.length() > 0)
						{
							if (locationDescription.toLowerCase().equals(cityName.toLowerCase()))
							{
								cityData = new LocationData(locationId, locationDescription, locationType);
								foundCity = true;
							}	
						}
						
					}
					
				}
				
				parser.next();
				
			}
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return cityData;
		
	}
	
}
